package org.pzy.java.concurrency;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author pzy
 */
public class UserThreadFactory implements ThreadFactory {

    private final String namePrefix;
    private final AtomicInteger nextId = new AtomicInteger(1);

    public UserThreadFactory(String whatFutureOfGroup) {
        namePrefix = "From UserThreadFactory's " + whatFutureOfGroup + "-Worker-";
    }

    @Override
    public Thread newThread(Runnable task) {
        String name = namePrefix + nextId.getAndIncrement();
        return new Thread(null, task, name);
    }

    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor1 = new ThreadPoolExecutor(2, 4, 3000, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(), new UserThreadFactory("pool-1"));

        ThreadPoolExecutor poolExecutor2 = new ThreadPoolExecutor(3, 6, 3000, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(), new UserThreadFactory("pool-2"));

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            poolExecutor1.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "--->Hello World" + finalI);
            });
            poolExecutor2.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "--->Hello World" + finalI);
            });
        }
    }
}

